﻿#region Usings

using System;
using System.Linq;
using System.Linq.Expressions;
using Ninject;
using Rail.Net.Core.Interfaces.Data.Cacheable;
using Rail.Net.Core.Model;

#endregion

namespace Rail.Net.Data.Caching
{
    public class CacheableRepository<T> : Repository<T> where T : BaseIdentifiable
    {
        //public CacheableRepository()
        //{
        //}
        //public CacheableRepository(DataContext context)
        //    : base(context)
        //{
        //}

        [Inject]
        public ICacheProvider CacheProvider { get; set; }

        //public override IQueryable<T> All()
        //{
        //    return CacheProvider.GetOrCreateCache(base.All()).AsQueryable();
        //}

        public override IQueryable<T> All(params Expression<Func<T, object>>[] includeProperties)
        {
            return CacheProvider.GetOrCreateCache(base.All(includeProperties)).AsQueryable();
        }

        public override IQueryable<T> All(int index = 0, int size = 50, params Expression<Func<T, object>>[] includeProperties)
        {
            var skipCount = index * size;
            return CacheProvider.GetOrCreateCache(base.All(index, size, includeProperties)).AsQueryable();
        }

        public override IQueryable<T> Filter(Expression<Func<T, bool>> predicate, int index = 0, int size = 50)
        {
            return CacheProvider.GetOrCreateCache(base.Filter(predicate, index, size)).AsQueryable();
        }

        public override IQueryable<T> Filter(Expression<Func<T, bool>> predicate)
        {
            return CacheProvider.GetOrCreateCache(base.Filter(predicate)).AsQueryable();
        }

        public override T Create(T instance)
        {
            CacheProvider.ClearCache<T>();
            return base.Create(instance);
        }

        public override int Update(T instance)
        {
            CacheProvider.ClearCache<T>();
            return base.Update(instance);
        }

        public override int Delete(T instance)
        {
            CacheProvider.ClearCache<T>();
            return base.Delete(instance);
        }
    }
}